/**
 * 请求处理
 */
import axios from "axios"
import router from "./router"
import ELement from "element-ui"


axios.defaults.baseURL = "http://localhost:7027/"

const request = axios.create({
    //该对象超时时间为5s
    timeout: 5000,
    headers: {
        'Content-Type': "application/json;charset=utf-8"
    }
})
//前置拦截，拦截请求，验证token
request.interceptors.request.use(config => {
    config.headers["authorization"] = localStorage.getItem("token")
    return config
})

//后置拦截，拦截响应，验证是否异常
request.interceptors.response.use(response => {
        let res = response.data
        if (res.code === 200) {
            return response
        } else {
            ELement.Message.error(!res.msg ? '发生未知错误' : res.msg)
            return Promise.reject(response.data.msg)
        }
    },
    error => {
        //如果没有权限状态401，则跳转到登录页
        if (error.response.status === 401) {
            router.push("/login")
        }
        //如果返回数据为空，则提示
        if (error.response.data) {
            error.massage = error.response.data.msg
        }
        //element弹窗提示错误信息
        ELement.Message.error(error.massage, {duration: 3000})
        return Promise.reject(Response.data.msg)
    }
)

export default request